﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace KouDai.Core
{
    public static class CommonEx
    {
        #region AsyncExtensions
        public static Task<WebResponse> GetResponseAsync(this WebRequest source)
        {
            return Task<WebResponse>.Factory.FromAsync(new Func<AsyncCallback, object, IAsyncResult>(source.BeginGetResponse), new Func<IAsyncResult, WebResponse>(source.EndGetResponse), null);
        }

        public static Task<Stream> GetRequestStreamAsync(this WebRequest source)
        {
            return Task<Stream>.Factory.FromAsync(new Func<AsyncCallback, object, IAsyncResult>(source.BeginGetRequestStream), new Func<IAsyncResult, Stream>(source.EndGetRequestStream), null);
        }

        public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<bool>();
            using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
            {
                if (task != await Task.WhenAny(task, tcs.Task))
                {
                    throw new OperationCanceledException(cancellationToken);
                }
            }
            return await task;
        }
        #endregion

        #region ObservableExtensions

        public static void ToObservableCollection<T>(this List<T> list, ObservableCollection<T> observables)
        {
            foreach (T value in list)
            {
                observables.Add(value);
            }
        }

        #endregion


    }
}
